<template>
  <el-card class="list-page">
    <el-form
      :inline="true"
      :model="formInline"
      :label-position="'right'"
      ref="formRef"
      class="demo-form-inline"
      :label-width="'130px'"
    >
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="集采标段名称/编号" prop="purchaseLotLike">
            <el-input
              v-model="formInline.purchaseLotLike"
              placeholder="集采标段名称/编号"
              @change="handleSearch"
              class="width-custom170"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="工程技术组" prop="engineTechnologyGroup">
            <el-select
              v-model="formInline.engineTechnologyGroup"
              placeholder="工程技术组"
              @change="handleSearch"
              class="width-custom170"
              clearable
            >
              <el-option
                class="default-option"
                v-for="item in engineTechnologyGroupList"
                :label="item.dicValue"
                :key="item.dicCode"
                :value="item.dicCode"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="招采进度" prop="attractProgress">
            <el-select
              v-model="formInline.attractProgress"
              placeholder="招采进度"
              @change="handleSearch"
              class="width-custom170"
              clearable
            >
              <el-option
                class="default-option"
                v-for="item in attractProgressList"
                :label="item.dicValue"
                :key="item.dicCode"
                :value="item.dicCode"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item style="float: right">
            <el-button type="primary" @click="addClick"> 新增 </el-button>
            <el-button @click="handleReset">重置</el-button>
            <el-button type="primary" @click="handleSearch">查询</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-skeleton
      style="height: calc(100vh - 300px)"
      :rows="8"
      :loading="loading"
      animated
    >
    </el-skeleton>
    <el-table
      :data="state.tableData"
      stripe
      v-show="!loading"
      style="width: 100%; margin-top: 20px"
      :height="'calc(100vh - 300px)'"
      row-key="id"
      ref="tableRef"
      @selection-change="selectionChange"
      :header-cell-style="{
        background: '#F7F9FD',
        color: '#000',
        height: '48px',
        borderTop: '1px soild #E4E8F2'
      }"
    >
      <template #empty>
        <el-empty :image-size="150" description="暂无数据"></el-empty>
      </template>
      <el-table-column type="index" label="序号" width="50" fixed="left">
        <template v-slot="scope">
          <span>{{
            (formInline.pageNum - 1) * formInline.pageSize + scope.$index + 1
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="purchaseLotName"
        label="集采标段名称"
        width="180"
        fixed="left"
      ></el-table-column>
      <el-table-column
        prop="purchaseLotNum"
        label="集采标段编号"
        width="180"
        fixed="left"
      ></el-table-column>
      <el-table-column
        prop="projectLotName"
        label="项目标段名称"
        width="180"
      ></el-table-column>
      <el-table-column
        prop="engineTechnologyGroupDesc"
        label="工程技术组"
        width="120"
      ></el-table-column>
      <el-table-column
        prop="attractWayDesc"
        label="招采方式"
        width="80"
      ></el-table-column>
      <el-table-column
        prop="reviewWayDesc"
        label="评审方式"
        width="120"
      ></el-table-column>
      <el-table-column
        prop="attractProgressDesc"
        label="招采进度"
        width="160"
      ></el-table-column>
      <el-table-column
        prop="purchaseLotYear"
        label="集采标段年度"
        width="110"
      ></el-table-column>
      <el-table-column
        prop="projectLotAmount"
        label="项目标段预算金额(万元)"
        width="170"
      ></el-table-column>
      <el-table-column
        prop="principalName"
        label="集采标段负责人"
        width="160"
      ></el-table-column>
      <el-table-column
        prop="purchasePlanFirstReviewTime"
        label="采购技术方案初审时间"
        width="160"
      ></el-table-column>
      <el-table-column
        prop="purchasePlanFinalVersionTime"
        label="采购技术方案定稿时间"
        width="160"
      ></el-table-column>
      <el-table-column label="附件" width="100">
        <template #default="{ row }">
          <el-button
            type="text"
            class="shot-text"
            @click="uploadFileClick(row)"
          >
            共{{ row.documentCount || 0 }}个文件
          </el-button>
        </template>
      </el-table-column>
      <el-table-column
        prop="createUserName"
        label="创建人"
        width="120"
      ></el-table-column>
      <el-table-column
        prop="createTime"
        label="创建时间"
        width="160"
      ></el-table-column>
    </el-table>
    <re-pagination
      :total="total"
      v-show="total > 0"
      v-model:page="formInline.pageNum"
      v-model:limit="formInline.pageSize"
      @pagination="handleSearch(formInline.pageNum)"
    />
    <el-dialog
      v-model="dialogForm.visible"
      :title="dialogForm.title"
      destroy-on-close
      width="720px"
      @close="handleCancel"
    >
      <div class="tips">
        新增标段前请与总部工程部工程技术组确认，仅适用于立项批准在招标之后的标段
      </div>
      <el-form
        ref="dialogFormRef"
        :model="formState"
        :rules="Rules"
        label-width="250px"
        class="doc-dia"
      >
        <el-form-item label="项目标段名称：" prop="projectLotName">
          <el-input
            class="width-custom250"
            v-model="formState.projectLotName"
            clearable
            placeholder="项目标段名称"
          />
        </el-form-item>
        <el-form-item label="项目标段预算金额：" prop="projectLotAmount">
          <el-input-number
            class="width-custom210"
            v-model="formState.projectLotAmount"
            placeholder="项目标段预算金额"
            :controls="false"
            precision="6"
            :min="0"
            :max="Number(projectInfo.approvalAmount)"
          >
          </el-input-number>
          <span>万元</span>
        </el-form-item>
        <el-form-item label="集采标段：" prop="purchaseLotId">
          <el-select
            class="width-custom250"
            v-model="formState.purchaseLotId"
            clearable
            filterable
            remote
            placeholder="集采标段"
            :remote-method="(e: any) => {
              getPurchaseLotList(e)
            }"
          >
            <el-option
              v-for="item in purchaseLotList"
              :key="item.id"
              :label="`${item.purchaseLotName}(${item.purchaseLotNum})`"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="采购技术方案初审时间："
          prop="purchasePlanFirstReviewTime"
        >
          <el-date-picker
            class="width-custom250"
            v-model="formState.purchasePlanFirstReviewTime"
            type="date"
            placeholder="请选择时间"
          />
        </el-form-item>
        <el-form-item
          label="采购技术方案定稿时间："
          prop="purchasePlanFinalVersionTime"
        >
          <el-date-picker
            class="width-custom250"
            v-model="formState.purchasePlanFinalVersionTime"
            type="date"
            placeholder="请选择时间"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleSure">保存</el-button>
        </span>
      </template>
    </el-dialog>
    <UploadFile
      :showDialog="showUploadFile"
      :pitchDetail="pitchDetail"
      @submit="uploadFileSubmit"
    ></UploadFile>
  </el-card>
</template>
<script lang="ts" setup>
import { reactive, ref, onMounted } from "vue";
import NotifMessage from "/@/utils/message/notification";
import RePagination from "/@/components/RePagination/index.vue";
import UploadFile from "./components/uploadFile.vue";
import {
  lotMappingProjectList,
  groupPurchaseLotList,
  saveProjectMapping
} from "/@/api/projects";
import { postDictList } from "/@/api/home";
import { storageLocal } from "/@/utils/storage";
import moment from "moment";
const formRef = ref<HTMLFormElement | null>(null) as any;
const dialogFormRef = ref<HTMLFormElement | null>(null) as any;
const loading = ref<boolean>(false);
const total = ref<number>(0);
const formInline = reactive({
  pageNum: 1,
  pageSize: 10,
  purchaseLotLike: "",
  engineTechnologyGroup: "",
  attractProgress: "",
  attractWay: "",
  purchaseLotYear: "",
  projectLike: "",
  principalId: "",
  createTime: []
});

const engineTechnologyGroupList = ref([]);
const attractProgressList = ref([]);
const showUploadFile = ref(false);
const pitchDetail = ref({});
const selectRows = ref([]);
const purchaseLotList = ref([]);
const projectInfo = storageLocal.getItem("projectInfo");

const dialogForm = ref({
  visible: false,
  title: "新增项目标段",
  type: "add"
});
const formState = reactive({
  projectLotName: "",
  projectLotAmount: undefined,
  purchaseLotId: "",
  purchasePlanFirstReviewTime: "",
  purchasePlanFinalVersionTime: ""
});
const Rules = {
  projectLotName: [
    {
      required: true,
      message: "请输入项目标段名称",
      trigger: "blur"
    }
  ],
  projectLotAmount: [
    { required: true, message: "请输入项目标段预算金额", trigger: "blur" }
  ],
  purchaseLotId: [
    { required: true, message: "请选择集采标段", trigger: "change" }
  ]
};

const state = reactive({
  tableData: []
}) as any;

onMounted(() => {
  getDictList("engine_technology_group"); // 工程技术组
  getDictList("attract_progress"); // 招采进度
  getTableData(formInline);
});
const getDictList = (dicType: string) => {
  postDictList({ dicType }).then((res: any) => {
    const { data, code } = res;
    if (code === 200) {
      switch (dicType) {
        case "engine_technology_group":
          engineTechnologyGroupList.value = data || [];
          break;
        case "attract_progress":
          attractProgressList.value = data || [];
          break;
      }
    }
  });
};

// 重置条件
const handleReset = (): void => {
  formRef.value.resetFields();
  getTableData(formInline);
};

// 根据条件进行搜索
const handleSearch = (page?: any) => {
  if (!page) {
    formInline.pageNum = 1;
  }
  getTableData(formInline);
};

//获取列表
const getTableData = async (obj: any) => {
  loading.value = true;
  try {
    const { code, data } = (await lotMappingProjectList({
      ...obj,
      projectId: projectInfo.id
    })) as any;
    if (code === 200) {
      state.tableData = data.list;
      total.value = data.rows;
    }
  } catch (err) {
    console.log(err);
  } finally {
    loading.value = false;
  }
};

const addClick = () => {
  dialogForm.value.type = "add";
  dialogForm.value.visible = true;

  formState.projectLotName = "";
  formState.projectLotAmount = undefined;
  formState.purchaseLotId = "";
  formState.purchasePlanFirstReviewTime = "";
  formState.purchasePlanFinalVersionTime = "";
};

const handleCancel = () => {
  dialogFormRef.value.resetFields();
  dialogForm.value.visible = false;
};

const handleSure = async () => {
  const isValid = await new Promise(resolve =>
    dialogFormRef.value.validate(resolve)
  );
  if (!isValid) {
    return;
  }
  const find = purchaseLotList.value.find(
    val => val.id === formState.purchaseLotId
  );
  const params = {
    ...formState,
    projectId: projectInfo.id,
    projectName: projectInfo.projectName,
    projectNum: projectInfo.projectCode,
    approvalAmount: projectInfo.approvalAmount,
    purchaseLotId: find.id,
    purchaseLotName: find.purchaseLotName,
    purchaseLotNum: find.purchaseLotNum,
    purchasePlanFirstReviewTime: formState.purchasePlanFirstReviewTime
      ? moment(formState.purchasePlanFirstReviewTime).format("YYYY-MM-DD")
      : "",
    purchasePlanFinalVersionTime: formState.purchasePlanFinalVersionTime
      ? moment(formState.purchasePlanFinalVersionTime).format("YYYY-MM-DD")
      : ""
  };
  const { code } = (await saveProjectMapping(params)) as any;
  if (code === 200) {
    NotifMessage.success("操作成功");
    dialogFormRef.value.resetFields();
    dialogForm.value.visible = false;
    handleSearch();
  }
};

const uploadFileClick = (row: any) => {
  if (!row.documentCount || row.documentCount === 0) {
    NotifMessage.error(`当前标段未上传附件`);
    return;
  }
  showUploadFile.value = true;
  pitchDetail.value = {
    ...row
  };
};

const uploadFileSubmit = (type: string) => {
  if (type === "update") {
    handleSearch();
    return;
  }
  showUploadFile.value = false;
  if (type === "sure") {
    handleSearch();
  }
};

const selectionChange = (rows: any) => {
  selectRows.value = rows;
};

const getPurchaseLotList = (e: any) => {
  groupPurchaseLotList({
    // projectId: projectInfo.id,
    purchaseLotLike: e,
    pageNum: 1,
    pageSize: 9999
  }).then((res: any) => {
    console.log(res);
    const { code, data } = res;
    if (code === 200) {
      purchaseLotList.value = data?.list || [];
    }
  });
};
</script>
<style lang="scss" scoped>
.el-icon-warning {
  color: #e45d5d !important;
}
.width-custom250 {
  width: 250px !important;
}
.width-custom210 {
  width: 210px !important;
  margin-right: 10px;
}
.width-custom170 {
  width: 170px !important;
}
.el-input-number::v-deep .el-input__inner {
  text-align: left !important;
}
</style>
<style lang="scss" scoped>
.shot-text {
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  -o-text-overflow: ellipsis;
  -webkit-line-clamp: 1;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  white-space: nowrap;
}
.filter-tree:deep {
  &.el-tree {
    position: absolute;
    top: 36px;
    width: 400px;
    max-height: 226px;
    overflow: auto;
    border: 1px solid #e4e8f2;
    z-index: 10;
  }
}
.tips {
  padding: 8px 16px;
  background: #fff7e8;
  font-size: 14px;
  line-height: 22px;
  color: #ff8c1a;
  margin-bottom: 16px;
}
::v-deep .el-dialog__body {
  box-sizing: border-box;
  padding: 16px 20px;
}
</style>
